package com.example.webflux.controller;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.time.Duration;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping
    public String hello(ServerWebExchange exchange, WebSession session, HttpMethod method) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        Object name = session.getAttribute("name");
        session.getAttributes().put("name", "张三");
        return "Hello World!";
    }

    @GetMapping("/mono")
    public Mono<String> helloMono(ServerHttpRequest request, ServerHttpResponse response) {
        URI uri = request.getURI();
        System.out.println("请求处理业务" + uri);
        HttpStatusCode statusCode = response.getStatusCode();
        System.out.println("响应状态码" + statusCode);
        return Mono.just("Hello World Mono!");
    }

    @GetMapping("/flux")
    public Flux<String> helloFlux() {
        return Flux.just("Hello World Flux!", "Hello World Flux2!");
    }

    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> sse() {
        return Flux.range(1, 10)
                .map(i -> {
                    return ServerSentEvent.builder("ha-" + i)
                            .id(i + "")
                            .comment("hei-" + i)
                            .event("haha")
                            .build();
                });
    }

}
